package cn.ludi.service.impl;

import cn.ludi.entity.LoginUser;
import cn.ludi.entity.Role;
import cn.ludi.entity.User;
import cn.ludi.entity.UserRole;
import cn.ludi.mapper.UserMapper;
import cn.ludi.mapper.UserRoleMapper;
import cn.ludi.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService, UserDetailsService {

    @Autowired
    private UserRoleMapper userRoleMapper;


    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name",username);
        //根据用户名查找用户
        User user = baseMapper.selectOne(queryWrapper);
        //抛出业务异常
        if(null == user){
            throw new RuntimeException("用户名或密码错误");
        }

        List<String> roleList = userRoleMapper.selectRoleByUserId(user.getId());
        List<SimpleGrantedAuthority> simpleGrantedAuthorityList = new ArrayList<>();
        for (String r : roleList) {
            simpleGrantedAuthorityList.add(new SimpleGrantedAuthority(r));
        }
        //把数据封装成userDetails对象返回
        //去除权限字符串所有空值，防止报错
        roleList.removeIf(Objects::isNull);
        return new LoginUser(user,roleList);
    }
}
